package com.example.controller;


import com.example.pojo.Patriarch;
import com.example.pojo.Result;
import com.example.pojo.Teacher;
import com.example.service.PatriarchService;
import com.example.service.TeacherService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private PatriarchService patriarchService;

    @Autowired
    private TeacherService teacherService;


    @PostMapping("/login/patriarch")
    public Result login1(@RequestBody Patriarch patriarch){
        log.info("家长登录：{}",patriarch);

        Patriarch p = patriarchService.login(patriarch);

        if(p != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", p.getId());
            claims.put("name", p.getName());
            claims.put("username",p.getUsername());

            String jwt = JwtUtils.generateJwt(claims);

            return Result.success(jwt);
        }else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/login/teacher")
    public Result login2(@RequestBody Teacher teacher){
        log.info("教师登录：{}",teacher);

        Teacher t = teacherService.login(teacher);

        if(t != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", t.getId());
            claims.put("name", t.getName());
            claims.put("username",t.getUsername());

            String jwt = JwtUtils.generateJwt(claims);

            return Result.success(jwt);
        }else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/login/admin")
    public Result login3(@RequestBody Teacher teacher){
        log.info("管理员登录：{}",teacher);

        Teacher t = teacherService.login2(teacher);

        if(t != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", t.getId());
            claims.put("name", t.getName());
            claims.put("username",t.getUsername());

            String jwt = JwtUtils.generateJwt(claims);

            return Result.success(jwt);
        }else {
            return Result.error("用户名或密码错误");
        }
    }
}
